package com.graduate.examapp.view.activity

import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.airbnb.lottie.LottieAnimationView
import com.blankj.utilcode.util.GsonUtils
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.graduate.examapp.R
import com.graduate.examapp.adapter.ViewpagerAdapter
import com.graduate.examapp.entity.LoginData
import com.graduate.examapp.entity.UserInfoFactory
import com.graduate.examapp.service.MQTTService
import com.graduate.examapp.view.base.BaseActivity
import com.graduate.examapp.view.customview.setSelected
import com.graduate.examapp.view.customview.setUnselected
import com.graduate.examapp.view.fragment.DataFragment
import com.graduate.examapp.view.fragment.HomeFragment
import com.graduate.examapp.view.fragment.RangeFragment
import com.graduate.examapp.view.fragment.TeacherFragment
import com.z.fileselectorlib.FileSelectorSettings
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import java.net.URLConnection

class MainActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        UserInfoFactory.sharedPreference = getSharedPreferences("user", Context.MODE_PRIVATE)
        val userInfo = getSharedPreferences("user", Context.MODE_PRIVATE)?.getString("user_info", null)
        val loginData = GsonUtils.fromJson(userInfo, LoginData::class.java)
        UserInfoFactory.loginData = loginData

        val userType = UserInfoFactory.loginData?.userType ?: "teacher"
        Log.d("MainActivity", userType)
        Log.d("MainActivity", UserInfoFactory.loginData.toString())
        val fragments = ArrayList<Fragment>()
        fragments.add(HomeFragment())
        fragments.add(DataFragment())

        val iconList = ArrayList<Int>()
        iconList.add(R.raw.home)
        iconList.add(R.raw.data)

        val tabText = ArrayList<String>()
        tabText.add("个人中心")
        tabText.add("排考数据")

        //后端需要添加 userType字段
        if (userType == "admin") {
            fragments.add(RangeFragment())
            fragments.add(TeacherFragment())
            iconList.add(R.raw.range)
            iconList.add(R.raw.teacher)
            tabText.add("排考")
            tabText.add("教师管理")
        }

        val viewPager = findViewById<ViewPager2>(R.id.view_page)
        val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
        viewPager?.adapter = ViewpagerAdapter(this, fragments)

        TabLayoutMediator(tabLayout, viewPager) { tabItem, position ->
            val view = LayoutInflater.from(this).inflate(R.layout.custom_tabitem, null)
            val imageView = view.findViewById<LottieAnimationView>(R.id.tab_image)
            val textView = view.findViewById<TextView>(R.id.tab_text)
            imageView.setAnimation(iconList[position])
            imageView.setColorFilter(R.color.master)
            textView.text = tabText[position]
            tabItem.customView = view
        }.attach()

        tabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {

            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.setSelected(this@MainActivity)
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
                tab?.setUnselected(this@MainActivity)
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {

            }

        })
        Log.d("MainActivity", loginData.id)
        MQTTService.startService(this, loginData.id)
        Log.d("MainActivity", tabLayout.height.toString())
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.d("TeacherFragment", "文件上传")
        if (requestCode== FileSelectorSettings.FILE_LIST_REQUEST_CODE && resultCode == FileSelectorSettings.BACK_WITH_SELECTIONS){
            val extras = data?.extras
            val stringArrayList =
                extras?.getStringArrayList(FileSelectorSettings.FILE_PATH_LIST_REQUEST)
            if (stringArrayList?.size == 1) {
                val file = File(stringArrayList[0])
                val type = getMimeType(file) ?: "multipart/form-data"
                val part = MultipartBody.Part.createFormData("file", file.name, RequestBody.create(type.toMediaTypeOrNull(),file))

                //val fileRQ: RequestBody = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), file)
                //Log.d("TeacherFragment", fileRQ.toString())
                //val part: MultipartBody.Part = MultipartBody.Part.createFormData("teacher", file.name, fileRQ)
                //Log.d("TeacherFragment", part.toString())
                val fragment = supportFragmentManager.fragments[3] as TeacherFragment
                val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
                val info: NetworkInfo? = connectivityManager.getActiveNetworkInfo()
                if (info != null && info.isAvailable()) {
                    val name = info.getTypeName()
                    fragment.teacherViewModel.uploadTeacher(part)
                } else {
                    Toast.makeText(this, "网络连接不可用", Toast.LENGTH_LONG).show()
                }
            }
        }
    }
    fun getMimeType(file: File):String? = URLConnection.getFileNameMap().getContentTypeFor(file.name)
    companion object {
        fun start(context: Context) {
            val intent = Intent(context, MainActivity::class.java)
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }
}

